# 导入蓝图
from flask import render_template, session, current_app, request, jsonify, g

from info import redis_store, constants
from info.models import User, News, Category
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import index_blu


@index_blu.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')


@index_blu.route('/')
@user_login_data
def index():
    # 查询用户数据的代码已删除
    user = g.user

    # 获取到当前登录用户的id
    user_id = session.get("user_id")
    # 通过id获取用户信息
    user = None
    if user_id:
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)

    # 获取点击排行数据
    news_list = None
    try:
        #查询数据点击量降序 只查询前10条
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
        # print(news_list)
    except Exception as e:
        current_app.logger.error(e)

    click_news_list = []
    #遍历新闻列表 把里面的新闻对象转换字典
    for news in news_list if news_list else []:
        click_news_list.append(news.to_basic_dict())

    # 获取新闻分类数据
    categories = Category.query.all()
    # 定义列表保存分类数据
    categories_list = []

    for category in categories:
        #拼接内容
        categories_list.append(category.to_dict())

    data = {
        "user_info":user,
        'click_news_list' : click_news_list,
        'categories_list':categories_list
    }

    return render_template('news/index.html', data=data)

# 新闻分类
@index_blu.route('/newslist')
def get_news_list():
    """
    获取指定分类的新闻列表
    1获取参数
    2校验参数
    3查询数据
    4返回数据
    :return:
    """

    #1获取参数
    arges_dict = request.args
    #页数
    page = arges_dict.get("page","1")
    #每页数量
    per_page = arges_dict.get("per_age",constants.HOME_PAGE_MAX_NEWS)
    #分类id
    category_id = arges_dict.get("cid","1")
    #

    #2校验参数
    try:
        # 转换为数字类型
        page = int(page)
        per_page = int(per_page)
        category_id = int(category_id)
        # print('page=%d'%page)
        # print('per_page=%d'%per_page)
        # print('category_id=%d'%category_id)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')

    #3查询数据并分页
    filters = []
    #如果分类id不为１　那么添加分类ｉｄ的过滤，如果等于１就获取当前新闻就好
    if category_id !=1:
        filters.append(News.category_id == category_id)

    try:
        #把filters解包传入 false是为了让获取的参数不报错
        pagination = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
        #获取查询出来的数据
        news_list = pagination.items
        #获取到总页数
        total_page = pagination.pages
        #当前页对象
        current_page = pagination.page

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg = "数据查询失败")

    news_li = []
    for news in news_list:
        news_li.append(news.to_basic_dict())

    # print(news_li)

    #４返回数据
    return jsonify(errno=RET.OK,errmsg="OK",totalPage=total_page,currentPage=current_page,news_list=news_li,
                   cid=category_id)




































